import { app, BrowserWindow, ipcMain, dialog } from 'electron';
import * as path from 'path';
import { browserManager } from './browserManager';
import { generateUserAgent, getMacAddress, getAllMacAddresses } from './utils';
import { syncService } from './syncService';
import { apiClient } from './apiClient';

// 获取应用根目录
const APP_PATH = app.isPackaged 
  ? path.join(process.resourcesPath, 'app')
  : path.join(__dirname, '../..');

console.log('Main process started - Testing hot reload');
console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('APP_PATH:', APP_PATH);

// 单实例检查
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  console.log('Another instance is already running, quitting...');
  dialog.showMessageBox({
    type: 'info',
    title: '应用已在运行',
    message: 'YinianDa Fingerprint Browser已在运行中，请勿重复打开。',
    buttons: ['确定']
  });
  app.quit();
} else {
  console.log('First instance, continuing...');
  
  // 当第二个实例启动时，激活第一个实例
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    console.log('Second instance detected, activating first instance...');
    
    // 如果主窗口存在，激活它
    if (mainWindow) {
      if (mainWindow.isMinimized()) {
        mainWindow.restore();
      }
      mainWindow.focus();
      mainWindow.show();
    }
    
    dialog.showMessageBox({
      type: 'info',
      title: '应用已在运行',
      message: 'YinianDa Fingerprint Browser已在运行中，已为您激活现有窗口。',
      buttons: ['确定']
    });
  });
}

// 在开发环境中启用热重载
try {
  if (process.env.NODE_ENV === 'development' && false) { // 暂时禁用热重载
    console.log('Enabling electron-reloader...');
    const reloader = require('electron-reloader');
    reloader(module, {
      debug: true,
      watchRenderer: false,
      ignore: [
        /node_modules|[/\\]\./,
        /src[/\\]renderer/
      ]
    });
    console.log('Electron reloader configured');
  } else {
    console.log('Hot reload disabled for debugging');
  }
} catch (err) {
  console.error('Failed to enable electron-reloader:', err);
}

// 主窗口引用
let mainWindow: BrowserWindow | null = null;

// 设置IPC处理器
function setupIpcHandlers() {
  // 生成User Agent
  ipcMain.handle('generate-user-agent', () => {
    return generateUserAgent();
  });

  // 获取MAC地址
  ipcMain.handle('get-mac-address', () => {
    try {
      const macAddress = getMacAddress();
      return { success: true, data: macAddress };
    } catch (error) {
      console.error('Failed to get MAC address:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取MAC地址失败' };
    }
  });

  // 获取所有MAC地址
  ipcMain.handle('get-all-mac-addresses', () => {
    try {
      const macAddresses = getAllMacAddresses();
      return { success: true, data: macAddresses };
    } catch (error) {
      console.error('Failed to get all MAC addresses:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取所有MAC地址失败' };
    }
  });

  // 启动浏览器
  ipcMain.handle('launch-browser', async (event, config) => {
    try {
      if (!config || typeof config !== 'object') {
        throw new Error('无效的配置数据');
      }
      // 兼容google自动化参数
      await browserManager.launchBrowser({
        ...config,
        googleAuto: config.googleAuto,
        googleKeyword: config.googleKeyword,
        googleDomain: config.googleDomain
      });
      return { success: true, id: config.id };
    } catch (error) {
      console.error('Failed to launch browser:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '启动浏览器失败'
      };
    }
  });

  // 停止浏览器实例
  ipcMain.handle('stop-browser', async (event, id) => {
    try {
      if (!id || typeof id !== 'string') {
        throw new Error('无效的实例ID');
      }
      await browserManager.stopBrowser(id);
      return { success: true };
    } catch (error) {
      console.error('Failed to stop browser:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : '停止浏览器失败'
      };
    }
  });

  // 获取浏览器状态
  ipcMain.handle('get-browser-status', (event, id) => {
    try {
      if (!id || typeof id !== 'string') {
        throw new Error('无效的实例ID');
      }
      const status = browserManager.getBrowserStatus(id);
      return status || { isRunning: false, lastChecked: Date.now(), inProgress: false };
    } catch (error) {
      console.error('Failed to get browser status:', error);
      return { isRunning: false, lastChecked: Date.now(), inProgress: false };
    }
  });

  // 获取所有浏览器状态
  ipcMain.handle('get-all-browser-statuses', () => {
    try {
      const statusMap = browserManager.getAllBrowserStatuses();
      // 将Map转换为普通对象以确保IPC传输正确
      const statusObj: { [key: string]: any } = {};
      statusMap.forEach((status, id) => {
        statusObj[id] = {
          isRunning: Boolean(status.isRunning),
          lastChecked: Number(status.lastChecked),
          inProgress: Boolean(status.inProgress),
          action: status.action
        };
      });
      return statusObj;
    } catch (error) {
      console.error('Failed to get all browser statuses:', error);
      return {};
    }
  });

  // 状态更新事件转发已在模块加载时设置

  // 同步相关处理器
  // 上传备份
  ipcMain.handle('upload-backup', async (event, userId: string, token: string) => {
    try {
      console.log('Uploading backup for user:', userId);
      const result = await syncService.uploadBackup(userId, token);
      return result;
    } catch (error) {
      console.error('Failed to upload backup:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '备份上传失败'
      };
    }
  });

  // 下载备份
  ipcMain.handle('download-backup', async (event, userId: string, token: string) => {
    try {
      console.log('Downloading backup for user:', userId);
      const result = await syncService.downloadBackup(userId, token);
      
      // 如果下载成功，配置会通过前端重新加载
      if (result.success) {
        console.log('Backup downloaded successfully');
      }
      
      return result;
    } catch (error) {
      console.error('Failed to download backup:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '备份下载失败'
      };
    }
  });

  // 检查备份状态
  ipcMain.handle('check-backup', async (event, userId: string, token: string) => {
    try {
      console.log('Checking backup for user:', userId);
      const result = await syncService.checkBackup(userId, token);
      return result;
    } catch (error) {
      console.error('Failed to check backup:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '检查备份状态失败'
      };
    }
  });

  // 测试代理连接
  ipcMain.handle('test-proxy', async (event, config) => {
    try {
      console.log('Testing proxy for config:', config.id);
      const result = await browserManager.testProxy(config);
      return result;
    } catch (error) {
      console.error('Failed to test proxy:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '代理测试失败'
      };
    }
  });

  // 获取代理连通性状态
  ipcMain.handle('get-proxy-auth-status', async (event, config) => {
    try {
      console.log('Getting proxy connectivity status for config:', config.id);
      const result = await browserManager.getProxyAuthStatus(config);
      return result;
    } catch (error) {
      console.error('Failed to get proxy connectivity status:', error);
      return {
        authenticated: false,
        message: error instanceof Error ? error.message : '获取代理连通性状态失败'
      };
    }
  });

  // 获取所有代理连通性状态
  ipcMain.handle('get-all-proxy-auth-statuses', async (event, configs) => {
    try {
      console.log('Getting all proxy connectivity statuses');
      const result = await browserManager.getAllProxyAuthStatuses(configs);
      // 将Map转换为普通对象以确保IPC传输正确
      const statusObj: { [key: string]: any } = {};
      result.forEach((status, id) => {
        statusObj[id] = status;
      });
      return statusObj;
    } catch (error) {
      console.error('Failed to get all proxy connectivity statuses:', error);
      return {};
    }
  });

  // 导航浏览器到指定URL
  ipcMain.handle('navigate-browser', async (event, browserId: string, url: string) => {
    try {
      console.log(`Navigating browser ${browserId} to: ${url}`);
      const result = await browserManager.navigateBrowser(browserId, url);
      return { success: true, result };
    } catch (error) {
      console.error('Failed to navigate browser:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '导航失败'
      };
    }
  });

  // Cookie 相关处理器
  // 获取浏览器 cookie（从服务器）
  ipcMain.handle('get-browser-cookie-from-server', async (event, instanceId: string) => {
    try {
      console.log(`Getting browser cookie from server for instance: ${instanceId}`);
      
      const response = await apiClient.getBrowserCookie(instanceId);
      return { success: true, cookies: response.cookie ? JSON.parse(response.cookie) : [] };
    } catch (error) {
      console.error('Failed to get browser cookie from server:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取cookie失败'
      };
    }
  });

  // 报告 cookie 到服务器
  ipcMain.handle('report-cookie-to-server', async (event, instanceId: string, cookie: string) => {
    try {
      console.log(`Reporting cookie to server for instance: ${instanceId}`);
      
      const success = await apiClient.reportCookie(instanceId, cookie);
      return { success };
    } catch (error) {
      console.error('Failed to report cookie to server:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '报告cookie失败'
      };
    }
  });

  // 设置 API token
  ipcMain.handle('set-api-token', async (event, token: string) => {
    try {
      console.log('Setting API token');
      apiClient.setToken(token);
      return { success: true };
    } catch (error) {
      console.error('Failed to set API token:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '设置token失败'
      };
    }
  });

  // 获取 cookie 监控状态（调试用）
  ipcMain.handle('get-cookie-monitoring-status', async (event) => {
    try {
      console.log('Getting cookie monitoring status');
      const status = browserManager.getCookieMonitoringStatus();
      return { success: true, status };
    } catch (error) {
      console.error('Failed to get cookie monitoring status:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取cookie监控状态失败'
      };
    }
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    autoHideMenuBar: true, // 隐藏菜单栏但保留标题栏
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: true,
      devTools: process.env.NODE_ENV === 'development', // 只在开发环境启用开发者工具
      // 生产环境额外禁用
      ...(process.env.NODE_ENV !== 'development' && {
        devTools: false,
        enableRemoteModule: false,
        allowRunningInsecureContent: false,
        experimentalFeatures: false,
        enableBlinkFeatures: '',
        disableBlinkFeatures: 'AutomationControlled'
      })
    },
    icon: path.join(APP_PATH, 'build/icon.png'),
    // 保留标题栏，只隐藏菜单
    titleBarStyle: 'default',
    frame: true
  });

  // 隐藏菜单栏
  mainWindow.setMenu(null);

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:8080').catch(err => {
      console.error('Failed to load development server:', err);
      dialog.showErrorBox('加载错误', '无法连接到开发服务器，请确保开发服务器已启动。');
    });
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html')).catch(err => {
      console.error('Failed to load app:', err);
      dialog.showErrorBox('加载错误', '应用加载失败，请检查文件是否完整。');
    });
    
    // 生产环境完全禁用开发者工具
    mainWindow.webContents.on('devtools-opened', () => {
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.closeDevTools();
      }
    });

    // 禁用右键菜单
    mainWindow.webContents.on('context-menu', (event) => {
      event.preventDefault();
    });

    // 禁用所有开发者工具相关的快捷键
    mainWindow.webContents.on('before-input-event', (event, input) => {
      const key = input.key.toLowerCase();
      const modifiers = input.control || input.meta || input.alt || input.shift;
      
      // 禁用F12
      if (key === 'f12') {
        event.preventDefault();
        return;
      }
      
      // 禁用Ctrl+Shift+I (开发者工具)
      if (input.control && input.shift && key === 'i') {
        event.preventDefault();
        return;
      }
      
      // 禁用Ctrl+Shift+C (元素检查)
      if (input.control && input.shift && key === 'c') {
        event.preventDefault();
        return;
      }
      
      // 禁用Ctrl+Shift+J (控制台)
      if (input.control && input.shift && key === 'j') {
        event.preventDefault();
        return;
      }
      
      // 禁用Ctrl+U (查看源代码)
      if (input.control && key === 'u') {
        event.preventDefault();
        return;
      }
      
      // 禁用Ctrl+Shift+U (查看源代码)
      if (input.control && input.shift && key === 'u') {
        event.preventDefault();
        return;
      }
    });

    // 禁用webContents的开发者工具方法
    const originalOpenDevTools = mainWindow.webContents.openDevTools;
    mainWindow.webContents.openDevTools = () => {
      console.log('Developer tools access blocked in production');
      return;
    };

    // 禁用webContents的toggleDevTools方法
    const originalToggleDevTools = mainWindow.webContents.toggleDevTools;
    mainWindow.webContents.toggleDevTools = () => {
      console.log('Developer tools toggle blocked in production');
      return;
    };
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // 处理渲染进程崩溃
  mainWindow.webContents.on('crashed', () => {
    dialog.showErrorBox('错误', '渲染进程崩溃，请重启应用。');
    app.quit();
  });
  
    // 设置状态更新事件转发 - 在窗口创建完成后设置
  browserManager.on('statusUpdate', (id: string, status: any) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('browser-status-update', id, status);
    }
  });
}

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  dialog.showErrorBox('错误', '发生未知错误，请重启应用。');
  app.exit(1);
});

// 初始化应用
app.whenReady().then(() => {
  // 只有在获得单实例锁时才继续初始化
  if (!gotTheLock) {
    console.log('No lock obtained, skipping initialization...');
    return;
  }

  // 生产环境禁用开发者工具
  if (process.env.NODE_ENV !== 'development') {
    // 禁用所有开发者工具相关的菜单
    app.on('browser-window-created', (event, window) => {
      window.webContents.on('devtools-opened', () => {
        window.webContents.closeDevTools();
      });
    });
  }

  console.log('🚀 Application starting...');
  console.log('📝 Test log output - If you see this message, the logging system is working');
  console.log('🔧 Current environment:', process.env.NODE_ENV);
  
  // 先设置IPC处理器
  setupIpcHandlers();
  // 然后创建窗口
  createWindow();

  console.log('✅ Application initialization completed');

  // 设置退出处理
  let isQuitting = false;
  let quitTimeout: NodeJS.Timeout;

  app.on('before-quit', async (event) => {
    // 如果已经在退出过程中,直接返回
    if (isQuitting) return;

    console.log('Preparing to quit...');
    event.preventDefault();
    isQuitting = true;

    // 设置超时强制退出
    quitTimeout = setTimeout(() => {
      console.log('Force quitting due to timeout...');
      app.exit(0);
    }, 3000);

    try {
      // 清理所有浏览器实例
      await browserManager.stopAllBrowsers();
      console.log('All browsers stopped, quitting...');
      
      // 清除超时
      clearTimeout(quitTimeout);
      app.exit(0);
    } catch (error) {
      console.error('Error during cleanup:', error);
      clearTimeout(quitTimeout);
      app.exit(1);
    }
  });

}).catch(err => {
  console.error('Failed to initialize app:', err);
  dialog.showErrorBox('启动错误', '应用启动失败，请重试。');
  app.exit(1);
});

app.on('window-all-closed', () => {
  console.log('All windows closed');
  // 只有在获得单实例锁的情况下才处理窗口关闭
  if (gotTheLock && process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // 只有在获得单实例锁的情况下才处理激活事件
  if (gotTheLock && mainWindow === null) {
    createWindow();
  }
});

// 确保在退出前清理资源
app.on('will-quit', () => {
  console.log('Application will quit');
}); 